<template>
<!--  搜索框组件-->
  <TableSearch  :deletSome="deletSomes"  @addRow="addUser" @deletSome="deletSomeUsers"  :search-fields="searchFields"  @search="handleSearch"  @reset="handleReset"></TableSearch>
  <!-- 表格组件 -->
  <TableComponent
      :columns="columns"
      :tableData="tableData"
      :loading="loading"
      :deletSome="deletSomes"
      @delete="handleDelete"
      @editRow="editUserRow"
      @somedelete="handleSomeDelete"
  />
  <pagination  :current-page="currentPage"  :page-size="pageSize"  :total="total"   @size-change="handleSizeChange"
 @current-change="handleCurrentChange"></pagination>
</template>
<script setup>
import { ref, reactive, onMounted } from 'vue';

import  pagination from '@/components/pagination/index.vue';
import TableSearch from '@/components/TableSearch/index.vue';
import TableComponent from '@/components/DataTable/index.vue';

import api from '@/api/userLogin.ts'
import router from "@/router/index.js";
import {ElLoading, ElMessage, ElMessageBox} from "element-plus";

// 侧边栏折叠状态
const sidebarCollapsed = ref(false);

let deletSomes= true;
// 搜索字段
const searchFields = reactive([
  { label: '用户名', prop: 'username', type: 'input' },
  { label: '手机号码', prop: 'phone', type: 'input' },
  // { label: '状态', prop: 'status', type: 'select', options: [
  //     { label: '全部', value: '' },
  //     { label: '正常', value: 1 },
  //     { label: '禁用', value: 0 },
  //   ]},
  // { label: '创建时间', prop: 'createTime', type: 'date-range' },
]);

// 表格列定义
const columns = [
  { prop: 'userId', label: 'userId', width: 80 },
  { prop: 'username', label: 'username', width: 120 },
   { prop: 'password', label: 'password', width: 120 },
  { prop: 'role', label: 'role', width: 180 },

  { prop: 'points', label: 'points', width: 120 },
  { prop: 'phone', label: 'phone', width: 300 },
  { prop: 'createName', label: '创建人', width: 180 },
  { prop: 'createTime', label: '创建时间', width: 180 },
  { prop: 'amendName', label: '修改人', width: 180 },
  { prop: 'amendTime', label: '修改时间', width: 120 },
  // { prop: 'status', label: '状态', width: 100, formatter: (row) => row.status ? '正常' : '禁用' },
  
  // { prop: 'action', label: '操作', width: 180, fixed: 'right' },
];

// 表格数据
const tableData = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
let users;
const Search =ref({})
// 加载表格数据
const loadData = async () => {
  loading.value = true;

  try {
    let datas
    Search.value.pageNum = currentPage.value;
    Search.value.pageSize = pageSize.value;
    console.log(Search.value);
    // const response = await api.selectAll(Search.value);
    const response = await api.selectAll(Search.value);

    tableData.value = response.data.list || [];
    total.value = response.data.total || 0;
    console.log('加载数据成功:', response);
    if (response.code == 200) {
      // 开发环境调试日志
    } else {
      // API返回了错误码
      throw new Error(response.message || '获取数据失败');
    }
  } catch (error) {
    console.error('加载数据失败:', error);
    // 友好的错误提示
    ElMessage.error({
      message: error.message || '加载数据失败，请稍后重试',
      duration: 3000
    });

    // 重置数据防止显示旧数据
    tableData.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};
function addUser() {
  router.push(`/user/create`);
}
// 批量删除
async function deletSomeUsers() {
  try {
    // 确认对话框
    const confirmResult = await ElMessageBox.confirm(
        '确定要批量删除这些用户吗？此操作不可撤销！',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    );

    if (confirmResult !== 'confirm') {
      return; // 用户点击了取消
    }

    // 极速模式：所有删除请求同时发起
    const loadingInstance = ElLoading.service({
      lock: true,
      text: '正在批量删除用户...',
      background: 'rgba(0, 0, 0, 0.7)'
    });

    const results = await Promise.allSettled(
        Object.values(users).map(user =>
            api.deletUser({ userId: user.userId })
                .then(() => ({ status: 'fulfilled', userId: user.userId }))
                .catch(error => ({ status: 'rejected', userId: user.userId, error }))
        )
    );

    // 关闭加载动画
    loadingInstance.close();

    // 生成统计报告
    const successCount = results.filter(r => r.status === 'fulfilled').length;
    const failedCount = results.filter(r => r.status === 'rejected').length;

    // 刷新数据
    await loadData();

    // 显示操作结果
    if (failedCount === 0) {
      ElMessage.success(`成功删除 ${successCount} 个用户`);
    } else if (successCount === 0) {
      ElMessage.error(`删除失败，所有 ${failedCount} 个用户均未删除成功`);
    } else {
      ElMessage.warning(
          `删除完成，成功 ${successCount} 个，失败 ${failedCount} 个`,
          { duration: 5000 }
      );
    }

    return {
      total: results.length,
      success: successCount,
      failed: failedCount,
      errors: results.filter(r => r.status === 'rejected').map(r => ({
        userId: r.userId,
        error: r.error.message
      }))
    };

  } catch (error) {
    // 用户可能点击了取消按钮，不需要处理
    if (error !== 'cancel' && error !== 'close') {
      ElMessage.error(`删除操作出错: ${error.message}`);
    }
    return null;
  }
}

function editUserRow(row) {
  router.push(`/user/${row.userId}/edit`);
  // sessionStorage.setItem("user",JSON);
}
// 处理搜索
const handleSearch = (params) => {
  console.log('Search params:', params);
  currentPage.value = 1;
  Search.value = params;
  loadData();
};

// 处理重置
const handleReset = () => {
  Search.value.username=''
  Search.value.phone=''
  currentPage.value = 1;
  loadData();
};

// 删除功能
const handleDelete = async (row) => {
  // 极速模式：所有删除请求同时发起
  try {
    await ElMessageBox.confirm(
        `确定要删除用户 "${row.username}" (ID: ${row.userId}) 吗？`,
        '删除确认',
        {
          confirmButtonText: '确认删除',
          cancelButtonText: '取消',
          type: 'warning',
          closeOnClickModal: false, // 防止误点
          beforeClose: async (action, instance, done) => {
            if (action === 'confirm') {
              instance.confirmButtonLoading = true;
              try {
                const loadingInstance = ElLoading.service({
                  lock: true,
                  text: '正在删除用户...',
                  background: 'rgba(0, 0, 0, 0.7)'
                });

                await api.deletUser({ userId: row.userId });
                done();
                // 关闭加载动画
                loadingInstance.close();
              } catch (error) {
                instance.confirmButtonLoading = false;
                // 关闭加载动画
                loadingInstance.close();
                throw error;
              }
            } else {
              done();
            }
          }
        }
    );

    // 删除成功后刷新数据
    await loadData();

    ElMessage({
      type: 'success',
      message: `用户 "${row.username}" 删除成功`,
      duration: 3000
    });

  } catch (error) {
    if (error !== 'cancel') {
      ElMessage({
        type: 'error',
        message: `删除失败: ${error.message || '未知错误'}`,
        duration: 5000
      });
    } else {
      ElMessage({
        type: 'info',
        message: '已取消删除操作',
        duration: 2000
      });
    }
  }
};
function handleSomeDelete(rows) {
   users=rows;
   console.log(rows,"获取多列的值")
}
// 处理每页数量变化
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  loadData();
};

// 处理页码变化
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  loadData();
};
function deleteclick() {

}
// 初始化加载数据
onMounted(() => {
  loadData();
});
</script>

<style scoped>
#app {
  font-family: Inter, Avenir, Helvetica, Arial, sans-serif;
  min-height: 100vh;
}
</style>
